<template>
  <div class="detail">
    <div class="detail-image">
      <u-image :src="detail.image" :height="500" mode="aspectFit"></u-image>
    </div>
    <u-line ></u-line>
    <div class="detail-box">
      <view class="demo-tag" v-if="detail.is_new === 0">
        <view class="demo-tag-owner">
          新品上架
        </view>
      </view>
      <div style="display: flex;align-items: center;justify-content: space-between">
        <view class="demo-title">
          {{detail.name}}
        </view>
       </div>
      <view style="display: flex;align-items: center;justify-content: space-between">
        <view class="demo-price">
          ￥{{detail.price}}起
        </view>
      </view>
      <view>

      </view>
      <u-gap height="20"></u-gap>
      <u-line ></u-line>
      <u-gap height="20"></u-gap>
      <u-section :font-size="36"  :show-line="false" title="商品介绍" :right="false"></u-section>
      <u-gap height="20"></u-gap>

      <u-line ></u-line>
    </div>

    <div style="padding: 0 20rpx">
      <u-parse :html="detail.remark"></u-parse>
    </div>
    <div class="goods-action">
      <div class="goods-icon" @click="openCart">
        <u-badge type="error" :count="carNum" :offset="[-10,-10]">
        </u-badge>
        <u-icon name="shopping-cart" color="#ff7043" size="48">
        </u-icon>
        <div>购物车</div>
      </div>
      <div class="goods-btn1" @click="openPopup(false)">加入购物车</div>
      <div class="goods-btn2" @click="openPopup(true)">立即购买</div>
    </div>

    <u-popup v-model="show" mode="bottom" border-radius="14">
      <div class="food-popup" style="padding-top: 40rpx">
        <div class="food-popup-item" v-for="item in foodCategoryList">
          <div class="food-popup-item-label">{{ item.name }}</div>
          <div class="food-popup-item-content">
            <div
                @click="changeFoodCategory(item, sub.name)"
                :class="['food-popup-item-value', item.check === sub.name ? 'active' : '']" v-for="sub in item.children">
              {{ sub.name }}
            </div>
          </div>

        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;
            border-top: 1px solid rgb(235, 235, 235);padding: 20rpx 0 10rpx 0">
          <div class="item-price-left" style="padding-left: 30rpx">
            <div class="item-price-unit">￥</div>
            <div class="item-price-value">{{ food.totalPrice }}</div>
          </div>
          <div style="display: flex;align-items: center;justify-content: flex-end;padding-right: 20px;">
            <u-icon name="minus-circle" color="#999" size="48" @click="onminus"></u-icon>
            <text style="margin: 0 20rpx;line-height: 48rpx">{{ food.count }}</text>
            <u-icon name="plus-circle-fill" color="#f15929" size="48" @click="onAdd"></u-icon>
          </div>
        </div>
        <div class="food-button" v-if="!isBuy">
          <div class="button" @click="show = false">取消</div>
          <div class="button button-primary" @click="onAddCart">加入购物车</div>
        </div>
        <div class="food-button" v-else>
          <div style="width: 100%" class="button button-primary" @click="onConfirm2">结算</div>
        </div>
      </div>
    </u-popup>
    <u-popup v-model="show2" mode="bottom" border-radius="14">
      <div class="food-popup cart-popup">
        <view class="item-container">
          <u-empty v-if="carList.length === 0" mode="car"></u-empty>
          <view class="thumb-box" v-for="(item1, index1) in carList" :key="index1">
            <image class="image-cart" :src="item1.image" mode="heightFix"></image>
            <div class="item-content">
              <div class="item-name">{{ item1.name }}</div>
              <div class="item-desc">{{ item1.spec_key }}</div>
              <div class="item-price">
                <div class="item-price-left">
                  <div class="item-price-unit">￥</div>
                  <div class="item-price-value">{{ isCompany ? item1.company_price :item1.price }}</div>
                </div>
                <div style="display: flex;align-items: center;justify-content: flex-end;padding-right: 20px;">
                  <u-icon name="minus-circle" color="#999" size="48" @click="onminusItem(item1)"></u-icon>
                  <text style="margin: 0 20rpx;line-height: 48rpx">{{ item1.count }}</text>
                  <u-icon name="plus-circle-fill" color="#f15929" size="48" @click="onAddItem(item1)"></u-icon>
                </div>
              </div>
            </div>
          </view>
        </view>

        <div class="food-button" v-if="carList.length">
          <div class="button button-primary" @click="onConfirm">结算</div>
        </div>
      </div>
    </u-popup>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: "index",
  data() {
    return {
      detail: {},
      goods_id: '',
      count: 0,
      food: {},
      show: false,
      foodCategoryList: [
      ],
      carList: [],
      show2: false,
      isBuy: false,
      baseUrl: this.$baseUrl
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    carNum() {
      let count = 0;
      this.carList.forEach((val) => {
        count += val.count;
      })
      return count;
    },
    isCompany() {
      return this.userInfo && this.userInfo.company_id
    }
  },
  onShow() {
    this.carList = uni.getStorageSync('carList') || [];
  },
  onLoad({ id }) {
    this.goods_id = id
    this.getDetail()
  },
  methods: {
    getDetail() {
      this.$api.goodsDetail(this.goods_id).then(res => {
        let spec = []
        if (res.spec) {
          spec = JSON.parse(res.spec)
        }
        this.detail = {
          ...res,
          spec,
        }
        console.log(this.detail)
      }).catch(err => {
        console.log(err)
      })
    },
    openCart() {
      this.show2 = true;
    },
    // 加入购物车
    onAddCart(){
      const item = this.food;
      let flag = false;
      this.carList.forEach((val) => {
        if(val.spec_key === item.spec_key) {
          val.count += item.count;
          flag = true;
        }
      })
      if(!flag) {
        this.carList.push({
          ...item,
        })
      }
      uni.setStorageSync('carList', this.carList)
      this.show = false;
    },
    onminusItem(item) {
      if (item.count > 0) {
        item.count--
      } else {
        this.carList.splice(this.carList.findIndex(val => val.id === item.id && val.spec_key === item.spec_key), 1)
      }
      uni.setStorageSync('carList', this.carList)
    },
    onAddItem(item) {
      item.count++
      uni.setStorageSync('carList', this.carList)
    },
    // 打开弹窗
    openPopup(isBuy) {
      this.isBuy = isBuy
      const item = this.detail
      this.foodCategoryList = item.spec.map(_item => {
        return {
          ..._item,
          check: '',
          children: _item.children.map(sub => {
            return {
              ...sub,
            }
          })
        }
      })
      // 默认选中每一个规格的第一个子规格
      this.foodCategoryList.forEach(item => {
        item.check = item.children[0].name
      })
      this.food = {
        ...item,
        spec_key: '',
        spec_check: [],
        totalPrice: 0,
        count: 1
      };
      this.show = true;
      this.updateCheckFood()
    },
    updateCheckFood() {
      let checkedList = this.foodCategoryList.filter(item => item.check)
      let spec_check = []
      checkedList.forEach(item => {
        item.children.forEach(sub => {
          if (sub.name === item.check) {
            spec_check.push({
              ...sub,
              pname: item.name
            })
          }
        })
      })
      this.food.spec_key = checkedList.map(item => {
        return item.check
      }).join(',')
      // spec_check里面的价格之和 * 总数量
      this.food.totalPrice = spec_check.reduce((total, item) => {
        if (this.isCompany) {
          return total + Number(item.company_price || 0)
        } else {
          return total + Number(item.price)
        }
      }, 0) * this.food.count
      this.food.spec_check = spec_check
    },
    changeFoodCategory(item, name) {
      // if (item.check === name) {
      //   item.check = ''
      // } else {
      //   item.check = name;
      // }
      item.check = name;
      this.updateCheckFood()
    },
    onAdd() {
      this.food.count++
      this.updateCheckFood()
    },
    onminus() {
      if(this.food.count > 1) {
        this.food.count--
        this.updateCheckFood()
      }
    },
    onConfirm() {
      if (!this.userInfo.id) {
        // 确认对话框
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/user/login'
              })
            }
          }
        })
        return;
      }
      if(this.carList.length === 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return ;
      }
      uni.setStorageSync('carList', [])
      uni.setStorageSync('buyList', this.carList)
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    },
    onConfirm2() {
      if (!this.userInfo.id) {
        // 确认对话框
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/user/login'
              })
            }
          }
        })
        return;
      }
      let carList = []
      // 先添加购物车
      const item = this.food;
      carList.push({
        ...item,
      })
      uni.setStorageSync('buyList', carList)
      this.show = false;
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    }
  }
}
</script>

<style lang="scss">
.detail {
  .goods-action {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    height: 120rpx;
    display: flex;
    align-items: center;
    background-color: #FFFFFF;
    color: #FFFFFF;
    .goods-icon {
      position: relative;
      font-size: 28rpx;
      color: #646566;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 0 10px;
      img {
        height: 36rpx;
        margin: 0 auto 2px;
      }
    }
    .goods-btn1 {
      width: 100%;
      margin-left: 5px;
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-weight: 500;
      font-size: 14px;
      border: none;
      border-top-left-radius: 999px;
      border-bottom-left-radius: 999px;
      background: linear-gradient(to right, #ffd01e, #ff8917);
    }
    .goods-btn2 {
      width: 100%;
      margin-right: 5px;
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-weight: 500;
      font-size: 14px;
      border: none;
      border-top-right-radius: 999px;
      border-bottom-right-radius: 999px;
      background: linear-gradient(to right, #ff6034, #ee0a24);
    }
    .goods-btn3 {
      width: 100%;
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-weight: 500;
      font-size: 14px;
      border: none;
      border-radius: 999px;
      background: #999999;
      box-sizing: border-box;
      margin: 0 20px;
    }

  }
  .detail-image {
    background-color: #ffffff;
  }
  .detail-box {
    padding: 20rpx;
    background-color: #ffffff;
  }
  .demo-title {
    font-size: 30rpx;
    margin-top: 5px;
    color: $u-main-color;
    margin-bottom: 10px;
  }

  .food-popup {
    padding-bottom: 20rpx;
    .food-button {
      display: flex;
      justify-content: space-between;
      padding: 0 20px 20px;

      .button {
        display: inline-block;
        line-height: 22px;
        padding: 10px 15px;
        margin: 12px 0 2px 0px;
        border-radius: 5px;
        width: 45%;
        text-align: center;
        background-color: rgba(255, 112, 67, .12549019607843137);
        border: 1px solid #ff7043;
        color: #ff7043;
      }
      .button-primary {
        background-color: #ff7043;
        color: #ffffff;
      }
    }
    .item-price-left {
      flex-grow: 1;
      display: flex;
      align-items: flex-end;
      color: rgb(223, 60, 57);
      .item-price-unit {
        padding-bottom: 8rpx;
        font-size: 20rpx;
        line-height: 20rpx;
      }
      .item-price-value {
        font-size: 32rpx;
        font-weight: bold;
      }
    }

    .food-popup-item {
      padding:16rpx 20px;
      padding-top: 0;
    }
    .food-popup-item-label {
      flex-shrink: 0;
      font-size: 14px;
      color: #666666;
      min-width: 60px;
    }
    .food-popup-item-content {
      flex-grow: 1;
      display: flex;
      flex-wrap: wrap;
    }
    .food-popup-item-value {
      display: inline-block;
      line-height: 22px;
      padding: 5px 15px;
      margin: 12px 15px 2px 0px;
      border-radius: 5px;
      min-width: 70px;
      text-align: center;
      background-color: #f5f5f5;
      border: 1px solid #f5f5f5;
      &.active {
        background-color: rgba(255, 112, 67, .12549019607843137);
        border: 1px solid #ff7043;
        color: #ff7043;
      }
    }
  }
  .cart-popup {
    background-color: #f8f7f8!important;
    padding: 20rpx;
    .item-container {
      min-height: 500rpx;
      background-color: #ffffff;
      padding: 20rpx;
      .thumb-box {
        border-bottom: 1px solid rgb(235, 235, 235);
      }
    }
    .food-button {
      .button {
        width: 100%;
      }
    }
  }
  .item-container {
    position: relative;
  }

  .image-cart {
    width: 120rpx;
    height: 120rpx;
  }
  .item-content {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .item-name {
      font-size: 28rpx;
      color: #080808;
    }
    .item-desc {
      color: #aaa!important;
      font-size: 24rpx;
      padding-top: 10rpx;
    }
    .check-button {
      display: inline-block;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      background-color: #f15929;
      color: #fff;
      font-size: 24rpx;
    }
    .check-button2 {
      display: inline-block;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      background-color: #ccc;
      color: #fff;
      font-size: 24rpx;
    }
    .item-price {
      display: flex;
      align-items: center;
      padding-top: 5rpx;
      width: 100%;
      justify-content: space-between;
      .item-price-left {
        flex-grow: 1;
        display: flex;
        align-items: flex-end;
        color: rgb(223, 60, 57);
        .item-price-unit {
          padding-bottom: 8rpx;
          font-size: 20rpx;
          line-height: 20rpx;
        }
        .item-price-value {
          font-size: 32rpx;
          font-weight: bold;
        }
      }
    }
  }
  .thumb-box {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 20rpx 0;
  }

  .demo-tag {
    display: flex;
    margin-top: 5px;
  }

  .demo-tag-owner {
    background-color: $u-type-error;
    color: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 10rpx 14rpx;
    border-radius: 50rpx;
    font-size: 24rpx;
    line-height: 1;
  }

  .demo-tag-text {
    border: 1px solid $u-type-primary;
    color: $u-type-primary;
    margin-left: 10px;
    border-radius: 50rpx;
    line-height: 1;
    padding: 4rpx 14rpx;
    display: flex;
    align-items: center;
    border-radius: 50rpx;
    font-size: 20rpx;
  }

  .demo-price {
    font-size: 40rpx;
    color: #fa3534;
    margin-top: 5px;
  }
  .demo-count {
    font-size: 28rpx;
    color: $u-type-info;
    margin-top: 5px;
  }
}

</style>
